package com.gitee.dictionary.handle;

import com.gitee.dictionary.base.BaseDictionaryEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Set;

/**
 * @author <a href="mailto:lin-mt@outlook.com">lin-mt</a>
 */
@MappedJdbcTypes({JdbcType.CHAR, JdbcType.VARCHAR})
public class DictionaryEnumsHandler<E extends BaseDictionaryEnum> extends BaseTypeHandler<E> {
    
    private final Set<TypeHandler<E>> dictionaryEnumHandlers;
    
    public DictionaryEnumsHandler(Set<TypeHandler<E>> dictionaryEnumHandlers) {
        this.dictionaryEnumHandlers = dictionaryEnumHandlers;
    }
    
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getCode());
    }
    
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.getEnumInstance(rs.getString(columnName));
    }
    
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.getEnumInstance(rs.getString(columnIndex));
    }
    
    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.getEnumInstance(cs.getString(columnIndex));
    }
    
    private E getEnumInstance(String code) {
        if (code == null) {
            return null;
        }
        E enumInstance = null;
        for (TypeHandler<E> dictionaryEnumHandler : this.dictionaryEnumHandlers) {
            if (dictionaryEnumHandler instanceof DictionaryEnumHandler) {
                enumInstance = ((DictionaryEnumHandler<E>) dictionaryEnumHandler).getEnumInstance(code);
                if (enumInstance != null) {
                    break;
                }
            }
        }
        return enumInstance;
    }
}
